var $customerIntentionTable = $('#productTable');//客户分析表格
// 获取当前日期：年、月
var thisYear = new Date().getFullYear().toString();
var thisMonth = (new Date().getMonth() + 1).toString();


//防止表头与表格不对齐
$(window).resize(function () {
    $customerIntentionTable.bootstrapTable('resetView');
});


$(function(){
    // 销售额度统计表 日期筛选控件
    $('#statisticsYear').datepicker({
        language: 'zh-CN',
        startView: 'decade',
        endView: 'decade',
        maxViewMode: 'decade',
        minViewMode: 'decade',
        format: 'yyyy',
        autoclose:true,
        todayHighlight: true,
    }).datepicker('setDate', thisYear).on('changeYear', function (ev) {
        var xTitle = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        $('#statisticsMonth').datepicker('clearDates');
        setTimeout(function () {
            // 销售额度数据初始化方法
            dataInit('analyse');
        }, 100);
    });
    $('#statisticsMonth').datepicker({
        language: 'zh-CN',
        startView: 'year',
        endView: 'year',
        maxViewMode: 'year',
        minViewMode: 'year',
        format: 'mm',
        autoclose:true,
        todayHighlight: true,
        clearBtn: true,
    }).datepicker('setDate', thisMonth).on('changeMonth', function () {
        setTimeout(function () {
            // 销售额度数据初始化方法
            dataInit('analyse');
        }, 100);
    }).on('clearDate', function () {
        setTimeout(function () {
            // 销售额度数据初始化方法
            dataInit('analyse');
        }, 100);
    });
    // 销售额度统计表数据初始化
    dataInit('analyse');

    // 销售产品分析 日期筛选控件
    $('#analysisYear').datepicker({
        language: 'zh-CN',
        startView: 'decade',
        endView: 'decade',
        maxViewMode: 'decade',
        minViewMode: 'decade',
        format: 'yyyy',
        autoclose:true,
        todayHighlight: true,
    }).datepicker('setDate', thisYear).on('changeYear', function (ev) {
        // $('#analysisMonth').datepicker('clearDates');
        $('#analysisMonth').val('');
        setTimeout(function () {
            $customerIntentionTable.bootstrapTable('refresh');
        }, 100);
    });
    $('#analysisMonth').datepicker({
        language: 'zh-CN',
        startView: 'year',
        endView: 'year',
        maxViewMode: 'year',
        minViewMode: 'year',
        format: 'mm',
        autoclose:true,
        todayHighlight: true,
        clearBtn: true,
    }).datepicker('setDate', thisMonth).on('changeMonth', function (e) {
        if ($('#analysisYear').val() == '') {
            $.alert({
                title: '系统提示',
                content: '请先选择年份！',
                buttons: {
                    confirm: {
                        text: '确定',
                        btnClass: 'btn-primary',
                        action: function (e) {
                            $('#analysisMonth').datepicker('clearDates');
                        }
                    },
                }
            });
            return;
        }
        setTimeout(function () {
            $customerIntentionTable.bootstrapTable('refresh');
        }, 100);
    }).on('clearDate', function () {
        if ($('#analysisYear').val() == '') {
            return;
        }
        setTimeout(function () {
            $customerIntentionTable.bootstrapTable('refresh');
        }, 100);
    });
    // 销售产品分析 到款时间
    $('#arriveTimeStart').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // inputs: $('.range')
    }).on('changeDate', function () {
        var startDate = $('#arriveTimeStart').val();
        $('#arriveTimeEnd').datepicker('setStartDate', startDate);
    });
    $('#arriveTimeEnd').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // startDate: new Date(startDate)
    }).on('changeDate', function () {
        var endDate = $('#arriveTimeEnd').val();
        $('#arriveTimeStart').datepicker('setEndDate', endDate);
    });
    // 销售产品分析 产品名称
    screenProduct();
    // 销售产品分析表格数据初始化
    finishOrderProduct();

    $('#allProductData').on('click', function () {
        $('#filterContent').collapse('hide');
        $('#filterContent input').val('');
        $('#filterContent select').val('').selectpicker('refresh');
        $(this).addClass('btn-primary');
        $('#analysFilter input').val('');
        $customerIntentionTable.bootstrapTable('refresh');
    });
    $('#analysFilter input').on('change', function () {
        if ($('#analysisYear').val() != '') {
            $('#allProductData').removeClass('btn-primary');
            $('#filterContent').collapse('hide');
        }
    });

    // 高级筛选
    $('#filterContent select').selectpicker({
        size: 15,
        countSelectedText: function () {
            return '已选 {0} 条'
        }
    });
    var $filterBtn = $('button[data-target="#filterContent"]');
    $('#filterContent').on('show.bs.collapse', function () {
        $filterBtn.addClass('btn-secondary').html('<label><i class="mdi mdi-close"></i></label>关闭筛选');
    }).on('hide.bs.collapse', function () {
        $filterBtn.removeClass('btn-secondary').html('<label><i class="mdi mdi-filter-outline"></i></label>高级筛选');
    });
});

/**
 * 功能：高级筛选产品下拉列表初始化
 * */
function screenProduct() {
    $.ajax({
        url: '/returnMoney/selectShelfProductList',
        type: 'get',
        datatype: 'json',
        success: function (data) {
            if (data.code == '000000') {
                var memberProduct = data.data['memberShelfProductList'];
                var noMemberProduct = data.data['nonMemberShelfProductList'];
                var productDom = '';
                if (memberProduct.length == 0 && noMemberProduct.length == 0) {
                    var singleProducts = memberProduct.length == 0 ? noMemberProduct : memberProduct;
                    if (singleProducts.length) {
                        productDom = '<option value="">不限</option>';
                        for (let i = 0; i < singleProducts.length; i++) {
                            productDom += '<option value="' + singleProducts[i].productName + '">' + singleProducts[i].productName + '</option>';
                        }
                    } else {
                        productDom = '<option value="">不限</option>';
                    }
                } else {
                    var memberProductDom = '<optgroup label="会员产品">';
                    for (let i = 0; i < memberProduct.length; i++) {
                        memberProductDom += '<option value="' + memberProduct[i].productName + '">' + memberProduct[i].productName + '</option>';
                    }
                    memberProductDom += '</optgroup>';

                    var noMemberProductDom = '<optgroup label="非会员产品">';
                    for (let i = 0; i < noMemberProduct.length; i++) {
                        noMemberProductDom += '<option value="' + noMemberProduct[i].productName + '">' + noMemberProduct[i].productName + '</option>';
                    }
                    noMemberProductDom += '</optgroup>';
                    productDom =  memberProductDom + noMemberProductDom;
                }
                $('#productNames').html(productDom);
                $('#productNames').selectpicker('refresh');
            }
        }
    });
}

/**
 * 功能：高级筛选-重置
 * */
// 搜索
function searchProductData() {
    $('#analysFilter input').val('');
    $('#allProductData').removeClass('btn-primary');
    $customerIntentionTable.bootstrapTable('refreshOptions', {
        queryParams: function (params) {
            params.pageIndex = (params.offset / params.limit) + 1;  // 页码
            params.pageSize = params.limit;                         // 每页条数
            params.sortName = params.sort;                          // 排序列名
            params.sortOrder = params.order;                        // 排序方式

            // 高级筛选条件
            params.customerName = $('#customerName').val();         // 客户名称
            params.orderNumber = $('#orderNumber').val();           // 订单编号
            params.contractNumber = $('#contractNumber').val();     // 合同编号
            params.royaltyStatus = $('#royaltyStatus').val();       // 提成发放状态
            params.productNames = $('#productNames').val() ? $('#productNames').val().toString() : '';  // 产品名称
            params.arriveTimeStart = $('#arriveTimeStart').val();   // 到款时间 - 起
            params.arriveTimeEnd = $('#arriveTimeEnd').val();       // 到款时间 - 止

            return params;
        }
    });
}
// 重置
function clearAllData(_this) {
    var $filterContent = $(_this).parents('#filterContent');
    $filterContent.find('input').val('');
    $filterContent.find('select').val('').selectpicker('refresh');
    $('#analysFilter input').val('');
    $('#allProductData').addClass('btn-primary');

    // 显示全部数据
    // $('#allProductData').addClass('btn-primary');
    // $('#allProductData').trigger('click');

    $customerIntentionTable.bootstrapTable('refresh');
}


/**
 * 销售额度统计表 数据初始化
 */
function dataInit(id) {
    // 筛选条件: 年、月
    var params = '';
    var paramsYear = $('#statisticsYear').val();
    if ($('#statisticsMonth').val() != '') {
        params = 'month=' + paramsYear + '-' + $('#statisticsMonth').val();
    } else {
        params = 'year=' + paramsYear
    }

    $.ajax({
        url: '/returnMoney/selectPerformanceAnalysis?' + params,
        type: 'get',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        success: function (result) {
            if(result.code == '000000'){
                var datas = result.data;
                // 会员产品数量
                $('#vipProductCount').text(numFormat(datas.numberOfMemberProducts));
                // 会员产品销售额度
                $('#vipProductProductCount').text(numFormat(datas.salesQuotaOfMemberProducts));
                // 非会员产品数量
                $('#productCount').text(numFormat(datas.numberOfNonMemberProducts));
                // 非会员产品销售额度
                $('#productProductCount').text(numFormat(datas.salesQuotaOfNonMemberProducts));

                // Echarts图表配置
                let xData = function() {
                    let data = [];
                    if (datas.dateList){
                        for (let i = 0; i < datas.dateList.length; i++){
                            data.push(datas.dateList[i]);
                        }
                    } else if (datas.memberProductList){
                        for (let i = 0; i < datas.memberProductList.length; i++){
                            data.push(i + 1 + '月');
                        }
                    }
                    return data;
                }();
                let totalData = function() {
                    let total = [];
                    if (datas.memberProductList.length != datas.nonMemberProductList.length) {
                        alert('两组数据不匹配')
                        return;
                    }
                    datas.memberProductList.map((num, index) => {
                        total.push(Number(num) + Number(datas.nonMemberProductList[index]))
                    })
                    return total;
                }();
                let data = {
                    data1: datas.memberProductList,
                    data2: datas.nonMemberProductList,
                }

                //客户分析转化表
                let clientRate = document.getElementById(id)
                let myChart = echarts.init(clientRate);
                line_option.xAxis[0].data = xData;
                line_option.series[0].data = data.data1;
                line_option.series[1].data = data.data2;
                line_option.series[2].data = totalData;

                myChart.setOption(line_option);
                window.onresize = myChart.resize;
            }
        },
        error: function (res) {
            $.alert("加载失败");
        }
    })
}


/**
 * 功能：折线图初始化
 * */
var color = ['#6699ff',"#52cca3", '#caed8b'];
var line_option = {
    title: {
        text: '会员/非会员产品销售额度',
        left: '2%',
        top: '3%',
        textStyle: {
            color: '#999999',
            fontSize: '12',
        },
    },
    tooltip: {
        trigger: 'axis',
        extraCssText: 'font-size:14px;line-height:24px;color:#fff;background:#212947;opacity: 0.9;padding:10px 20px;box-shadow:0 0 3px rgba(0, 0, 0, 0.2)',
        formatter: function(params) {
            // console.log(params, color);
            let html = `<span style="">${params[0].axisValue}</span>`
            params.forEach(v => {
                html += `<div>
                            <span style="display:inline-block;color: #999999;margin-right:5px;border-radius:10px;width:10px;height:10px;border: 2px solid #FFFFFF;background-color:${color[v.componentIndex]};"></span>
                            ${v.seriesName}
                        <span style="color:${color[v.componentIndex]};font-size:18px;font-weight:700;padding-left: 10px;">${v.value}</span>`
            })
            return html
        }
    },
    legend: {
        data: ['会员产品销售额度', '非会员产品销售额度', '销售总额度'],
        top: '10',
        right: '2%',
    },
    xAxis: [{
        show: true,
        type: 'category',
        axisLine: {
            show: true,
            lineStyle:{
                color:'rgba(83, 83, 83,0.1)',
            },
        },
        axisTick:{
            show: false,
        },
        axisLabel: {
            color: '#999999',
            margin:20
        },
        splitLine: {
            show: false
        },
        boundaryGap: false,
        data: [],
    }],
    grid: {
        left: '10',
        right: '30',
        bottom: '10',
        borderWidth: 1,
        containLabel: true,
    },
    yAxis: [{
        name:'',
        type: 'value',
        min: 0,
        splitNumber: 4,
        splitLine: {
            //分隔线
            show: false,
            lineStyle: {
                //坐标轴在 grid 区域中的分隔线。
                color: 'rgba(83, 83, 83,0.1)'
            }
        },
        axisLine: {
            //坐标轴轴线相关设置
            show: true,
            lineStyle:{
                color:'rgba(83, 83, 83,0.1)',
            },
        },
        axisLabel: {
            show: true,
            textStyle: {
                color: '#999999',
            },
            margin:20
        },
        axisTick: {
            show: false,
        },
    }],
    series: [
        {
            name: '会员产品销售额度',
            type: 'line',
            smooth: true, //是否平滑
            showAllSymbol: false,
            symbol: 'circle',
            symbolSize: 2,
            lineStyle: {
                normal: {
                    color: '#6699ff',
                    width:2,
                },
            },
            itemStyle: {
                color: '#6699ff',
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(102, 153, 255, .8)' //rgba(61, 127, 255, 1) //rgba(106, 142, 216, .5)
                    },
                        {
                            offset: 1,
                            color: 'rgba(102, 153, 255, .8)'
                        }
                    ], false),
                }
            },
            data: [ ]
        },
        {
            name: '非会员产品销售额度',
            type: 'line',
            smooth: true, //是否平滑
            showAllSymbol: false,
            symbol: 'circle',
            symbolSize: 2,
            lineStyle: {
                normal: {
                    color: "#52cca3",
                    width:2,
                },
            },
            itemStyle: {
                color: "#52cca3",
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(82, 204, 163, .8)'
                    },
                        {
                            offset: 1,
                            color: 'rgba(82, 204, 163,.8)'
                        }
                    ], false),
                }
            },
            data: [ ]
        },
        {
            name: '销售总额度',
            type: 'line',
            smooth: true, //是否平滑
            showAllSymbol: false,
            symbol: 'circle',
            symbolSize: 2,
            lineStyle: {
                normal: {
                    color: "#B5EA55",
                    width:2,
                },
            },
            itemStyle: {
                color: "#B5EA55",
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(181, 234, 85, .5)'
                    },
                        {
                            offset: 1,
                            color: 'rgba(181, 234, 85, .5)'
                        }
                    ], false),
                }
            },
            data: [ ]
        },
    ]
};


/*
* 功能：销售产品分析
* */
function finishOrderProduct() {
    //先销毁表格
    $customerIntentionTable.bootstrapTable('destroy');
    $customerIntentionTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/returnMoney/selectReturnMoneyProductList',       // 请求地址
        // url: '/customerProduct/selectFinishOrderProductList',// 请求地址
        method: 'post',                                         // 请求方式
        contentType: "application/x-www-form-urlencoded",       // 请求内容类型
        dataType: "json",                                       // 数据类型
        striped: true,                                          // 是否显示行间隔色
        sortable: true,                                         // 是否启用排序
        sortOrder: "desc",                                      // 排序方式
        sortName: 'arriveTime',                                 // 排序字段
        cache: false,                                           // 是否使用缓存
        showColumns: false,                                     // 显示隐藏列
        showRefresh: false,                                     // 显示刷新按钮
        showToggle: false,                                      // 切换显示样式
        showFooter: false,                                      // 显示Table脚部
        pagination: true,                                       // 是否显示分页
        showPaginationSwitch: false,                            // 是否显示分页按钮
        clickToSelect: true,                                    // 是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,                                 // 最少要显示的列数
        undefinedText: '-',                                     // cell没有值时显示
        sidePagination: 'server',                               // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'returnMoneyId',
        idField: 'returnMoneyId',
        pageSize: 50,                                           // 每页的记录行数
        pageNumber: 1,                                          // 初始化加载第1页，默认第1页
        pageList: "[20, 50, 100]",                              // 可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 2,    // 右侧固定列

        queryParams: queryParams,                               // 查询参数
        columns: [
            {title: '主键', field: 'returnMoneyId', visible: false},
            {title: '产品名称', field: 'productName', name:'productName', align: 'left', sortable: true, valign: 'middle'},
            {title: '到款金额', field: 'arriveMoney', name:'arriveMoney', align: 'left', sortable: true, valign: 'middle'},
            {title: '订单编号', field: 'orderNumber', name:'orderNumber', align: 'left', sortable: true, valign: 'middle',
                formatter: function (value, row, index, field) {
                    if (row.productName == '客户充值' || value == null) {
                        return value;
                    } else {
                        return '<a href="#!" class="order-link">' + value + '</a>';
                    }
                },
                events: {
                    'click .order-link': function (e, value, row, index) {
                        parent.$(parent.document).data('multitabs').create({
                            iframe : true,
                            title : '订单详情',
                            url : '/front/orderManager/orderDetail?productOrderId=' + row.orderId + '&contractId=' + row.contractId
                        }, true);
                    }
                }
            },
            {title: '合同编号', field: 'contractNumber', name:'contractNumber', align: 'left', sortable: true, valign: 'middle',
                formatter: function (value, row, index, field) {
                    if (row.productName == '客户充值' || value == null) {
                        return value;
                    } else {
                        return '<a href="#!" class="contract-link">' + value + '</a>';
                    }
                },
                events: {
                    'click .contract-link': function (e, value, row, index) {
                        parent.$(parent.document).data('multitabs').create({
                            iframe : true,
                            title : '合同详情',
                            url : '/front/contractManager/contractDetail?contractId=' + row.contractId + '&urlType=1'
                        }, true);
                    }
                }
            },
            {title: '产品类型', field: 'productCategories', name:'productCategories', align: 'left', sortable: true, valign: 'middle'},
            {title: '提成发放状态', field: 'royaltyStatus', name:'royaltyStatus', align: 'left', sortable: true, valign: 'middle'},
            {title: '业绩换算比例', field: 'scoreConvertRatio', name:'scoreConvertRatio', align: 'left', sortable: true, valign: 'middle'},
            {title: '业绩金额', field: 'scoreMoney', name:'scoreMoney', align: 'left', sortable: true, valign: 'middle'},
            {title: '提成金额', field: 'royaltyMoney', name:'royaltyMoney',align: 'left', sortable: true, valign: 'middle'},
            {title: '录入人', field: 'createBy', name:'createBy', align: 'left', sortable: true, valign: 'middle'},
            {title: '到款时间', field: 'arriveTime', name:'arriveTime', align: 'left', sortable: true, valign: 'middle'},
            {title: '所属业务员', field: 'salesman', name:'salesman', align: 'left', sortable: true, valign: 'middle'},
            {title: '订单Id', field: 'orderId', visible: false},
            {title: '合同Id', field: 'contractId', visible: false}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total":  result.totalRecords///总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}


/*
* 功能：销售产品分析 - 参数
* */
function queryParams(params) {
    params.pageIndex = (params.offset / params.limit) + 1;  // 页码
    params.pageSize = params.limit;                         // 每页条数
    params.sortName = params.sort;                          // 排序列名
    params.sortOrder = params.order;                        // 排序方式
    if ($('#analysisYear').val() == '') {
        // 全部数据不传参数
    } else if ($('#analysisMonth').val() == '') {
        // 年
        params.year = $('#analysisYear').val();
    } else {
        // 年月
        params.month = $('#analysisYear').val() + '-' + $('#analysisMonth').val();
    }
    return params;
}


/**
 * 数字添加分隔符
 * */
function numFormat(num){
    var res = num.toString().replace(/\d+/, function(n){
        return n.replace(/(\d)(?=(\d{3})+$)/g,function($1){
            return $1+",";
        });
    })
    return res;
}